package com.xiajiucai.baiping.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.Base64;

import com.bumptech.glide.util.Util;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.xiajiucai.baiping.R;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

public class WeChatShareUtils {
    //    private static final int TIMELINE_SUPPORTED_VERSION = 0x21020001; // 微信4.2以上支持
    private static final int TIMELINE_SUPPORTED_VERSION = 0x27000D00;  // 判断微信版本是否为7.0.13及以上
    private static final String id = "xxxxxx"; //小程序原始id
    private static final String pageUrl = "https://mobile.billionbottle.com/wechat"; //兼容低版本的网页链接


    //IWXAPI是第三方app和微信通信的openapi接口
    private IWXAPI api;
    private Context context;
    public static WeChatShareUtils weChatShareUtils;

    public static WeChatShareUtils getInstance(Context context) {
        if (weChatShareUtils == null) {
            weChatShareUtils = new WeChatShareUtils();
        }
        if (weChatShareUtils.api != null) {
            weChatShareUtils.api.unregisterApp();
        }
        weChatShareUtils.context = context;
        weChatShareUtils.regToWx();
        return weChatShareUtils;
    }

    /**
     * 注册应用id到微信
     */
    public void regToWx() {
        //通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(context, "wxecc74a7f37974716", true);
        //将应用的appId注册到微信
        api.registerApp("wxecc74a7f37974716");
    }

    /**
     * 分享文字到朋友圈或者好友
     * @param text 文本内容
     * @param scene 分享方式：好友还是朋友圈
     * @return
     */
    public boolean shareText(String text, int scene) {
        //初始化一个WXTextObject对象，填写分享的文本对象
        WXTextObject textObject = new WXTextObject();
        textObject.text = text;
        return share(textObject, text, scene);
    }

    /**
     * @param bmp 图片的Bitmap对象
     * @param scene 分享方式：好友 WXSceneSession 还是朋友圈 WXSceneTimeline,收藏 WXSceneFavorite
     * @return
     */
    public boolean sharePic(Bitmap bmp, int scene) {
        //初始化一个WXImageObject对象
        WXImageObject imageObject = new WXImageObject();
        //设置缩略图
        Bitmap thump = Bitmap.createScaledBitmap(bmp, 300, 300, true);
        bmp.recycle();
        return share(imageObject, thump, scene);
    }

    /**
     * 分享网页到朋友圈或者好友，视频和音乐的分享和网页大同小异，只是创建的对象不同。
     * @param url         网页的url
     * @param title       显示分享网页的标题
     * @param thumb       图片的缩略图
     * @param description 对网页的描述
     * @param scene       分享方式：好友还是朋友圈
     * @return
     */
    public boolean shareUrl(String url, String title, Bitmap thumb, String description, int scene) {
        //初试话一个WXWebpageObject对象，填写url
        WXWebpageObject webPage = new WXWebpageObject();
        webPage.webpageUrl = url;
        //设置缩略图
        Bitmap tmb = Bitmap.createScaledBitmap(thumb, 150, 150, true);
        thumb.recycle();
        return share(webPage, title, tmb, description, scene);
    }

    /**
     * 分享小程序类型
     * @param url
     * @param title
     * @param thumb
     * @param description
     * @return
     */
    public boolean shareMiniProgram(String title, Bitmap thumb, String description, String appid, String url) {
        //初试话一个WXMiniProgramObject对象，填写url
        WXMiniProgramObject wxMiniProgramObject = new WXMiniProgramObject();
        wxMiniProgramObject.webpageUrl = pageUrl; //兼容低版本的网页链接
        wxMiniProgramObject.miniprogramType = WXMiniProgramObject.MINIPROGRAM_TYPE_TEST; //小程序类型，测试版
        wxMiniProgramObject.userName = appid;  //小程序原始id
        wxMiniProgramObject.path = url; //小程序的path

        //设置缩略图
        Bitmap tmb = Bitmap.createScaledBitmap(thumb, 300, 300, true);
        thumb.recycle();
        return share(wxMiniProgramObject, title, tmb, description, SendMessageToWX.Req.WXSceneSession);
    }


    private boolean share(WXMediaMessage.IMediaObject mediaObject, Bitmap thumb, int scene) {
        return share(mediaObject, null, thumb, null, scene);
    }

    private boolean share(WXMediaMessage.IMediaObject mediaObject, String description, int scene) {
        return share(mediaObject, null, null, description, scene);
    }

    private boolean share(WXMediaMessage.IMediaObject mediaObject, String title, Bitmap thumb, String description, int scene) {
        WXMediaMessage msg = new WXMediaMessage(mediaObject);
        if (title != null) {
            msg.title = title;
        }
        if (description != null) {
            msg.description = description;
        }
        if (thumb != null) {
            msg.thumbData = bmpToByteArray(thumb, true);
        }
        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = scene;
        return api.sendReq(req);
    }

    //判断是否支持转发到朋友圈
    //微信4.2以上支持，如果需要检查微信版本支持API的情况， 可调用IWXAPI的getWXAppSupportAPI方法,0x21020001及以上支持发送朋友圈
    //微信版本：当且仅当通过 IWXAPI.getWXAppSupportAPI() 接口获取到的值 >= 0x27000D00(7.0.13以上），才能支持FileProvider的方式进行分享。
    public boolean isSupportWX() {
        int wxSdkVersion = api.getWXAppSupportAPI();
        return wxSdkVersion >= TIMELINE_SUPPORTED_VERSION;
    }

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        int i;
        int j;
        if (bmp.getHeight() > bmp.getWidth()) {
            i = bmp.getWidth();
            j = bmp.getWidth();
        } else {
            i = bmp.getHeight();
            j = bmp.getHeight();
        }

        Bitmap localBitmap = Bitmap.createBitmap(i, j, Bitmap.Config.RGB_565);
        Canvas localCanvas = new Canvas(localBitmap);

        while (true) {
            localCanvas.drawBitmap(bmp, new Rect(0, 0, i, j), new Rect(0, 0, i, j), null);
            if (needRecycle)
                bmp.recycle();
            ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
            localBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                    localByteArrayOutputStream);
            localBitmap.recycle();
            byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();
            try {
                localByteArrayOutputStream.close();
                return arrayOfByte;
            } catch (Exception e) {
                // F.out(e);
            }
            i = bmp.getHeight();
            j = bmp.getHeight();
        }
    }

    /**
     * 将网络资源图片转换为Bitmap 该方法调用时要放在子线程中
     * @param imgUrl 网络资源图片路径
     * @return Bitmap
     */
    public static Bitmap netToLoacalBitmap(String imgUrl) {
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;
        try {
            in = new BufferedInputStream(new URL(imgUrl).openStream(), 1024);
            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, 1024);
            copy(in, out);
            out.flush();
            byte[] data = dataStream.toByteArray();
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            data = null;
            return bitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Bitmap sizeCompress(Bitmap bmp , int ratio) {
        // 压缩Bitmap到对应尺寸
        Bitmap result = Bitmap.createBitmap(bmp.getWidth() / ratio, bmp.getHeight() / ratio, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        Rect rect = new Rect(0, 0, bmp.getWidth() / ratio, bmp.getHeight() / ratio);
        canvas.drawBitmap(bmp, null, rect, null);
        return result;
    }

    private static void copy(InputStream in, OutputStream out)
            throws IOException {
        byte[] b = new byte[1024];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }


    private Bitmap base64ToBitmap(String base64Data) {
        String base64 = base64Data.replace("data:image/png;base64,", "");
        byte[] bytes = Base64.decode(base64, Base64.DEFAULT);
        if (bytes == null) {
            return null;
        } else {
            return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        }
    }

    /**
     * 分享图片到朋友圈
     * @param context
     */
    public void share111(Context context){
        Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), R.mipmap.s);

        //初始化 WXImageObject 和 WXMediaMessage 对象
        WXImageObject imgObj = new WXImageObject(bmp);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;

        //设置缩略图
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 20, 20, true);
        bmp.recycle();
        msg.thumbData = bmpToByteArray(thumbBmp, true);

        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneTimeline;

        //调用api接口，发送数据到微信
        api.sendReq(req);
    }
}


